/*
 * Copyright 2016 Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mingmen.canting.caigourenyuan;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.defineview.PayPassDialog;
import com.mingmen.canting.defineview.PayPassView;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.immersionbar.ImmersionBar;
import com.mingmen.canting.model.PeiSongDetailModel;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.util.ToolList;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;


/**
 * <p>
 * ListView形式的侧滑菜单，支持横向和竖向的。
 * </p>
 * Created by Yan Zhenjie on 2016/7/27.
 */
public class QueRenShouZiCaiActivity extends Activity {

    @BindView(R.id.text_return)
    TextView textReturn;
    @BindView(R.id.linear_return)
    LinearLayout linearReturn;
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.mToolbar)
    Toolbar mToolbar;
    QueRenZiCaiAdapter queRenAdapter;
    @BindView(R.id.recycle_queren)
    SwipeRecyclerView recycle_queren;
    LinearLayoutManager layoutManager;

    @BindView(R.id.btn_submit)
    Button btn_submit;


    String token;

    @BindView(R.id.supplierName)
    TextView supplierName;
    @BindView(R.id.checkbox_parent)
    CheckBox checkbox_parent;

    List<PeiSongDetailModel.DataBean.DetailsBean> detailsBeanList = new ArrayList<>();
    String billId;

    List<String> billDetailIds = new ArrayList<>();
    List<String> getBillDetailIds = new ArrayList<>();
    int flag = 0;
    String supplierNameStr;
    String supplierId;
    String partCancelFlag;
    String partArriveFlag;
    String partRefuseFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_querenzicai);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        textCenter.setText("确认收货");
        billId = getIntent().getStringExtra("billId");
        supplierId = getIntent().getStringExtra("supplierId");
        Log.d("supplierId", billId);
        supplierNameStr = getIntent().getStringExtra("supplierName");
        supplierName.setText(supplierNameStr);
        token = (String) SharePreferenceUtil.get(this, "token", "");
        ImmersionBar.with(this).titleBar(mToolbar)
                .navigationBarColor(R.color.black).init();
        partCancelFlag = getIntent().getStringExtra("partCancelFlag");
        partArriveFlag = getIntent().getStringExtra("partArriveFlag");
        partRefuseFlag = getIntent().getStringExtra("partRefuseFlag");
        layoutManager = new LinearLayoutManager(this);
        recycle_queren.setLayoutManager(layoutManager);
        queRenAdapter = new QueRenZiCaiAdapter(this, detailsBeanList);

        recycle_queren.setAdapter(queRenAdapter);


        getData(token, billId, partCancelFlag, partArriveFlag, partRefuseFlag);


        queRenAdapter.setOnItemClickListener(new QueRenZiCaiAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int pos, List<PeiSongDetailModel.DataBean.DetailsBean> myLiveList) {
                switch (view.getId()) {
//                    case R.id.checkbox:
                    case R.id.content:
                    case R.id.checkbox:
                        for (PeiSongDetailModel.DataBean.DetailsBean cart : detailsBeanList) {
                            if (cart.isSelect()) {   //是否勾上去了
                                Log.d("勾选上了", "勾选上了");
                                flag = 1;
                                JSONObject jsonObject = new JSONObject();
                                try {
                                    jsonObject.put("billDetailId", cart.getBillDetailId());
                                    jsonObject.put("amount", cart.getConfirmAmount() + "");
                                    jsonObject.put("price", cart.getArrivePrice() + "");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                Log.d("JSONOBJECTOBJECT", jsonObject.toString());
                                billDetailIds.add(jsonObject.toString());
                                getBillDetailIds.add(cart.getBillDetailId());

                                Log.d("JSONOBJECTOBJECT", getBillDetailIds.toString());
                                ToolList.removeDuplicateWithOrder(getBillDetailIds);
                                ToolList.removeDuplicateWithOrder(billDetailIds);
                                if (getBillDetailIds.size() == detailsBeanList.size()) {
                                    flag = 0;
                                    checkbox_parent.setChecked(true);
                                } else {
                                    flag = 1;
                                }

                            } else {
                                Log.d("取消勾选", "取消勾选");
                                flag = 1;
                                checkbox_parent.setChecked(false);
                                if (billDetailIds.size() > 0) {
                                    for (int i = 0; i < billDetailIds.size(); i++) {
                                        if (billDetailIds.get(i).contains(cart.getBillDetailId())) {
                                            billDetailIds.remove(i);
                                        }
                                    }
                                }
                                if (getBillDetailIds.size() > 0) {
                                    for (int i = 0; i < getBillDetailIds.size(); i++) {
                                        if (getBillDetailIds.get(i).contains(cart.getBillDetailId())) {
                                            getBillDetailIds.remove(i);
                                        }
                                    }
                                }
                                ToolList.removeDuplicateWithOrder(billDetailIds);
                                Log.d("applyListapply", billDetailIds.toString());
                                ToolList.removeDuplicateWithOrder(getBillDetailIds);
                            }
                        }
                        break;
                    case R.id.lyaout_shishou:

                        payDialog3(pos, myLiveList, 0);
                        break;
                    case R.id.layout_shijia:

                        payDialog3(pos, myLiveList, 1);
                        break;

                }
            }


        });

        checkbox_parent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    flag = 0;
                    for (int i = 0; i < detailsBeanList.size(); i++) {
                        Log.d("onCheckedChanged", detailsBeanList.get(i).getBillDetailId());
                        detailsBeanList.get(i).setSelect(true);
                        JSONObject jsonObject = new JSONObject();
                        try {
                  /*          jsonObject.put("commodityId", detailsBeanList.get(i).getCommodityId());
                            jsonObject.put("commodityAmount", detailsBeanList.get(i).getPrice() + "");
                            jsonObject.put("categoryId", "0");
                            jsonObject.put("mark", detailsBeanList.get(i).getApplyDetailId());*/
                            jsonObject.put("billDetailId", detailsBeanList.get(i).getBillDetailId());
                            jsonObject.put("amount", detailsBeanList.get(i).getConfirmAmount() + "");
                            jsonObject.put("price", detailsBeanList.get(i).getArrivePrice() + "");
                            getBillDetailIds.add(detailsBeanList.get(i).getBillDetailId());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                        Log.d("JSONOBJECTOBJECT", getBillDetailIds.toString());
                        ToolList.removeDuplicateWithOrder(getBillDetailIds);
                    }
                    queRenAdapter.notifyDataSetChanged();
                } else {
                    for (int i = 0; i < detailsBeanList.size(); i++) {
                        detailsBeanList.get(i).setSelect(false);
                    }
                    getBillDetailIds.clear();
                    queRenAdapter.notifyDataSetChanged();

                }
            }
        });

    }

    String sendStr;

    public void getData(String token, String billId, String partCancelFlag, String partArriveFlag, String partRefuseFlag) {
        HttpResponse.getOrderInfo(token, billId, "", "", "", new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                sendStr = s;
                if (detailsBeanList.size() > 0) {
                    detailsBeanList.clear();
                }
                Log.d("ShopDetailActivityShopDetailActivity", s);
                PeiSongDetailModel peiSongDetailModel = new PeiSongDetailModel();
                peiSongDetailModel = GsonUtil.GsonToBean(s, PeiSongDetailModel.class);
//                detailsBeanList = peiSongDetailModel.getData().get(0).getDetails();
                detailsBeanList.addAll(peiSongDetailModel.getData().get(0).getDetails());
                queRenAdapter.setDataList(detailsBeanList);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    @OnClick({R.id.text_return, R.id.linear_return, R.id.btn_submit})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.text_return:
                finish();
                break;
            case R.id.linear_return:
                finish();
                break;
            case R.id.btn_register:
                break;

            case R.id.btn_submit:
                Log.d("QueRenShouActivity", billDetailIds.toString());
                if (TextUtils.isEmpty(billDetailIds.toString())) {
                    Toast.makeText(this, "请选择要收货商品", Toast.LENGTH_SHORT).show();
                } else if (billDetailIds.size() < 1) {
                    Toast.makeText(this, "请选择要收货商品", Toast.LENGTH_SHORT).show();
                } else {


                    Log.d("billDetailIds", billDetailIds.toString());

                    HttpResponse.setConfirmSupply(token, billDetailIds.toString(), new StringCallback(this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            BaseBean baseBean = new BaseBean();
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);

                            if (baseBean.getCode() == 0) {
                                EventBus.getDefault().post(2);
                                finish();
                            }
                            Toast.makeText(QueRenShouZiCaiActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();

                        }
                    });
                }


                break;
        }
    }

    public void onEventMainThread(Integer a) {
        if (a == 3) {
            finish();
        }
    }


    /**
     * 3 自定义方式
     */
    private void payDialog3(int pos, List<PeiSongDetailModel.DataBean.DetailsBean> myLiveList, int flag) {
        final PayPassDialog dialog = new PayPassDialog(this, R.style.dialog_pay_theme);
        //弹框自定义配置
        dialog.setAlertDialog(false)
                .setWindowSize(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.4f)
                .setOutColse(false) //点击外部是否消失
                .setGravity(R.style.dialogOpenAnimation, Gravity.BOTTOM);
        //组合控件自定义配置
        dialog.getPayViewPass()
                .setHintText("价格")
                .setForgetText("密码忘记?")
                .setForgetColor(getResources().getColor(R.color.colorAccent))
                .setForgetSize(16)
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String password) {
                        //6位输入完成回调
//                        Toast.makeText(mContext, "输入内容:" + password, Toast.LENGTH_SHORT).show();
                        Log.d("passwordpassword", password);

                        if (password.equals("")) {

                        } else {
                            Integer int_count = Integer.valueOf(password);
                            if (flag == 0) {
                                myLiveList.get(pos).setArriveAmount(int_count);

                            } else if (flag == 1) {
                                myLiveList.get(pos).setArrivePrice(int_count);
                            }

                            queRenAdapter.notifyDataSetChanged();

                        }


                    }

                    @Override
                    public void onPayClose() {
                        dialog.dismiss();
                        //关闭回调
                    }

                    @Override
                    public void onPayForget() {
                        dialog.dismiss();

                    }
                });
    }
}